/**
 * Copyright (c) 2014.
 * Private license for beyondts.
 * Contact beyondts for using, beyondts999@163.com
 */
package net.beyondts.mplug.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

/**
 * Project: beyondts-basic<br/>
 * Description: <br/>
 * Created at: 2014年8月16日<br/>
 * Owned by beyondts.
 * 
 * @author blazecrystal
 *
 * @version 1.0.0
 */
public class BeanFactory {
    /**
     * spring的上下文.
     */
    private static ApplicationContext context;

    /**
     * getter method for "context".
     * 
     * @return the context
     */
    public static ApplicationContext getContext() {
        return context;
    }


    /**
     * config spring using already defined ApplicationContext.
     * offen used for WebApplicationContext(spring mvc)
     * 
     * @param appContext
     */
    public static void initByApplicationContext(ApplicationContext appContext) {
        context = appContext;
    }

    /**
     * 根据名称（id）获得一个spring的bean实例.
     * 
     * @param name {@link String} bean的名称或id
     * @return {@link Object} spring的bean实例
     */
    public static Object getBean(String name) {
        if (context == null) {
            // loadContext();
            throw new NullPointerException(
                    "spring context hasn't been initialized");
        }
        return context.getBean(name);
    }

    public static Class<?> getType(String name) {
        if (context == null) {
            // loadContext();
            throw new NullPointerException(
                    "spring context hasn't been initialized");
        }
        return context.getType(name);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return clazz.cast(context.getBean(name));
    }

    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }

    public static Environment getEnvironment() {
        return context.getEnvironment();
    }

    public static String getProperty(String key) {
        return context.getEnvironment().getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        return context.getEnvironment().getProperty(key, defaultValue);
    }

    public static <T> T getProperty(String key, Class<T> clazz) {
        return context.getEnvironment().getProperty(key, clazz);
    }

    public static <T> T getProperty(String key, Class<T> clazz, T defaultValue) {
        return context.getEnvironment().getProperty(key, clazz, defaultValue);
    }
}
